public class L02L07 {

    public static void main(String[] args) {
        ListNode listNodeA = new ListNode(1, null);
        ListNode listNodeB = new ListNode(1, null);
        new Solution().getIntersectionNode(listNodeA, listNodeB);
    }

    public static class Solution {
        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            ListNode curA = headA;
            ListNode curB = headB;
            int lengthA = 0;
            int lengthB = 0;

            while (curA != null) {
                curA = curA.next;
                lengthA++;
            }
            while (curB != null) {
                curB = curB.next;
                lengthB++;
            }

            curA = headA;
            curB = headB;

            if (lengthA < lengthB) {
                int lengthTemp = lengthB;
                lengthB = lengthA;
                lengthA = lengthTemp;

                ListNode curTemp = curB;
                curB = curA;
                curA = curTemp;
            }

            int gap = lengthA - lengthB;
            while (gap-- > 0) {
                curA = curA.next;
            }

            while (curA != null && curB != null) {
                if (curA == curB) {
                    return curA;
                }
                curA = curA.next;
                curB = curB.next;
            }
            return null;
        }
    }
}
